# Time    : 2019/4/28 下午2:53
# Author  : zw
# File    : date_utils.py
# Software: PyCharm
# 返回各种时间的方法
import calendar
import datetime
import json

import _strptime

VAR_DAY_LIST = ['day1', 'day2', 'day3', 'day4', 'day5', 'day6', 'day7', 'day8', 'day9', 'day10',
                'day11', 'day12', 'day13', 'day14', 'day15', 'day16', 'day17', 'day18', 'day19', 'day20',
                'day21', 'day22', 'day23', 'day24', 'day25', 'day26', 'day27', 'day28', 'day29', 'day30', 'day31']

default_date = (
    '%Y-%m-%d %H:%M:%S',  # '2006-10-25 14:30:59'
    '%Y-%m-%d %H:%M',  # '2006-10-25 14:30'
    '%Y-%m-%d',  # '2006-10-25'
    '%m/%d/%Y %H:%M:%S',  # '10/25/2006 14:30:59'
    '%m/%d/%Y %H:%M',  # '10/25/2006 14:30'
    '%m/%d/%Y',  # '10/25/2006'
    '%m/%d/%y %H:%M:%S',  # '10/25/06 14:30:59'
    '%m/%d/%y %H:%M',  # '10/25/06 14:30'
    '%m/%d/%y',  # '10/25/06'
    '%Y-%m-%dT%H:%M:%S',  # '2012-03-27T00:00:00'
    '%Y-%m-%dT%H:%M:%S.%f',  # '2012-03-27T00:00:00.000'
    '%Y-%m-%dT%H:%M:%S.%fZ',  # '2012-03-27T00:00:00.000Z'
)


def format_date(value):

    if not value:
        return None

    for ft in default_date:

        _strptime._getlang = lambda: (None, None)
        try:
            return datetime.datetime.strptime(value, ft).date()
        except Exception:
            continue
    return None


def get_month_range(start_date=None):

    if not isinstance(start_date, datetime.date) and start_date:
        start_date = format_date(start_date)

    if not start_date:
        start_date = datetime.date.today().replace(day=1)
    else:
        start_date = start_date.replace(day=1)

    _, days_in_month = calendar.monthrange(start_date.year, start_date.month)
    end_date = start_date + datetime.timedelta(days=days_in_month)
    return start_date, end_date


def range_day_list(start_date, end_date, is_format=False):
    """
    返回开始至结束时间的所有时间
    :param start_date: 开始时间
    :param end_date: 结束时间
    :param is_format: 是否格式化为字符串
    :return: 时间list
    """
    #  返回开始时间至结束时间的所有时间格式数据。
    date_str_list = []
    while start_date <= end_date:
        date = start_date.strftime("%Y-%m-%d") if is_format else start_date
        date_str_list.append(date)
        start_date += datetime.timedelta(days=1)

    return date_str_list


def get_day_map(date_list):
    date_list1 = []
    for i, v in enumerate(date_list):
        date_list1.append({'name': VAR_DAY_LIST[i], 'value': v})
    return date_list1


class DateEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        return super().default(obj)
